﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;

namespace Yz.DB.EFCore.DBUtility
{
    public static class EFExtension
    {
        /// <summary>
        /// 判断是否是window平台
        /// </summary>
        /// <returns></returns>
        public static bool IsWin()
        {
            return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
        }
        /// <summary>
        /// 判断是否是sqlserver
        /// </summary>
        /// <returns></returns>

        public static bool IsSqlServer(this DatabaseFacade database)
        {
            return database.ProviderName.Equals("Microsoft.EntityFrameworkCore.SqlServer", StringComparison.Ordinal);
        }
        /// <summary>
        /// 把listmodel转换成datatable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <param name="hasKey"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(this IList<T> entitys, bool hasKey = false)
        {
            //检查实体集合不能为空
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("需转换的集合为空");
            }
            //取出第一个实体的所有Propertie
            Type entityType = entitys[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();

            //生成DataTable的structure
            //生产代码中，应将生成的DataTable结构Cache起来，此处略
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                Type colType = entityProperties[i].PropertyType;
                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    colType = colType.GetGenericArguments()[0];
                }
                DataColumn dc = new DataColumn(entityProperties[i].Name, colType);
                if (hasKey && entityProperties[i].CustomAttributes.Where(p => p.AttributeType == typeof(KeyAttribute)).Any())
                {
                    dc.Unique = true;
                }
                dt.Columns.Add(dc);
            }
            //将所有entity添加到DataTable中
            foreach (object entity in entitys)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    throw new Exception("要转换的集合元素类型不一致");
                }
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }


        public static EntityMap GetEntityMap(Type type, DbContext dbContext)
        {
            var entityMap = new EntityMap();
            var mapping = dbContext.Model.FindEntityType(type);
            string tableName = mapping.GetTableName();
            var properties = mapping.GetDeclaredProperties();
            foreach (var item in properties)
            {
                var keys = item.GetContainingKeys();
                if (keys != null && keys.Count() > 0)
                {
                    entityMap.KeyMaps.Add(new PropertyMap() { PropertyName = item.Name, ColumnName = item.GetColumnName() });
                }
                entityMap.PropertyMaps.Add(new PropertyMap() { PropertyName = item.Name, ColumnName = item.GetColumnName() });
            }
            entityMap.TableName = tableName;
            return entityMap;
        }
    }
}
